package rabbitmq

import (
	"context"
	"gitee.com/lipore/plume/mq"
	"github.com/pkg/errors"
	"github.com/rabbitmq/amqp091-go"
)

type Publisher struct {
	channel  *amqp091.Channel
	Exchange string
	Key      string
}

func (p *Publisher) Publish(ctx context.Context, body []byte) error {
	err := p.channel.PublishWithContext(ctx, p.Exchange, p.Key, false, false, amqp091.Publishing{
		ContentEncoding: "text/plain",
		Body:            body,
	})
	if err != nil {
		return errors.WithMessage(err, "failed to publish message")
	}
	return nil
}

func NewPublisherFactory(connection *amqp091.Connection) mq.PublisherFactory {
	return &PublisherFactory{
		conn: connection,
	}
}

type PublisherFactory struct {
	conn *amqp091.Connection
}

func (p *PublisherFactory) NewPublisher(topic string) (mq.Publisher, error) {
	channel, err := p.conn.Channel()
	if err != nil {
		return nil, errors.WithMessage(err, "failed to create channel")
	}
	return &Publisher{
		channel:  channel,
		Exchange: topic,
		Key:      "",
	}, nil
}
